package see.battle.adaptor;

import java.util.LinkedList;

import see.battle.Const;
import see.battle.message.BulletMessage;
import see.battle.message.Message;
import see.battle.message.OpponentFocusMessage;
import see.battle.message.StartGameMessage;
import see.battle.object.ObjectPool;

public class AIAdaptor implements Adaptor {
  Message _m;  
  private boolean _stop = false;
  private LinkedList<Message> _messages = new LinkedList<Message>();
  private ObjectPool _pool;
  private static final int minStepsBetweenBullets = 200;
  private int _steps = 0;
  private float _x = Const.screenMiddle - Const.backgroundLeft;
 
  public AIAdaptor(ObjectPool pool) {
    _pool = pool;
    _messages.addLast(new StartGameMessage(System.currentTimeMillis(), 
        (long)(Math.random() * 1000) + 1));
  }
  public void set_view(int view) {	  
  } 
  @SuppressWarnings("static-access")
  public void run() {
    int bulletNumber = Const.maxBulletNumber;
    while (true) {
      if (_stop) break;
      _steps += 1;
      _x += (Math.random() * 0.02 - 0.01);
      _x = Math.min(_x, Const.screenMiddle - Const.backgroundLeft + (float)0.2);
      _x = Math.max(_x, Const.screenMiddle - Const.backgroundLeft - (float)0.2);
      synchronized (_messages) {
        _messages.addLast(new OpponentFocusMessage(_x));
      }
      if (bulletNumber != 0 && _steps >= minStepsBetweenBullets) {
        long additionalShipDelay = -1;
        synchronized (_messages) {
          additionalShipDelay = _pool.proceedBullet(_x);
          if (additionalShipDelay >= 0) {
            float x = _x + (float)(Math.random() * 0.02 - 0.01); 
            additionalShipDelay = _pool.proceedBullet(x);
            _steps = 0;
            bulletNumber -= 1;
            _messages.addLast(new BulletMessage(System.currentTimeMillis(),
                x, additionalShipDelay));
          }
        }
      }
      try {
        Thread.currentThread().sleep(Const.updateDelay);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
  
  public void stop() {
    _stop = true;
  }

  public Message readNextMessage() {
    _m = null;
    synchronized (_messages) {
      if (_messages.size() != 0) {
        _m = _messages.getFirst();
        _messages.removeFirst();
      }
    }
    return _m;
  }

  //@Override
  public void sendFocusMessage(float focus) {
    // STUB
  }

  //@Override
  public void sendBulletMessage(long time, float position,
      long additionalTimeDelay) {
    // STUB    
  }
}
